/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.base.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.oss.OSSServer;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.utils.CacheUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.StoreProduct;
import com.chlitina.store.modules.base.entity.StoreSelfProduct;
import com.chlitina.store.modules.base.entity.StoreSelfProductCategory;
import com.chlitina.store.modules.base.service.StoreProductService;
import com.chlitina.store.modules.base.service.StoreSelfProductCategoryService;
import com.chlitina.store.modules.base.service.StoreSelfProductService;
import com.chlitina.store.modules.expert.utils.ExpertUtils;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.utils.StoreUtils;

/**
 * 店面自营产品Controller
 * @author liujiang
 * @version 2013-11-03
 */
@Controller
@SessionAttributes("parent")
@RequestMapping(value = Global.ADMIN_PATH+"/base/storeSelfProduct")
public class StoreSelfProductController extends BaseController {

	@Autowired
	private StoreSelfProductService storeSelfProductService;
	
	@Autowired
	private StoreProductService storeProductService;

	@Autowired
	private StoreSelfProductCategoryService storeSelfProductCategoryService;
	
	@ModelAttribute
	public StoreSelfProduct get(@RequestParam(required=false) Long id) {
		if (id != null){
			return storeSelfProductService.get(id);
		}else{
			return new StoreSelfProduct();
		}
	}
	
	private String getSelectPage(Page page, StoreSelfProductCategory parent, Integer status){
		Long select_selfProduct_id = (Long) CacheUtils.get("select_selfProduct_id");
		String currentId = "";
		if(select_selfProduct_id != null) {
	        int index = storeSelfProductService.getIndexById(select_selfProduct_id, parent, status);
	        ExpertUtils.setPageNoByCurrentId(page, index);
	        currentId = String.valueOf(select_selfProduct_id);
	        CacheUtils.remove("select_selfProduct_id");
		}
		return currentId;
	}

	@RequestMapping(value = {"list", ""})
	public String list(Long category_id, @RequestParam(required=false)Integer status, 
			StoreSelfProduct storeSelfProduct, HttpServletRequest request, HttpServletResponse response, Model model) {
		StoreSelfProductCategory parent = storeSelfProductCategoryService.get(category_id);
		String productName = request.getParameter("productName");
		Page<StoreSelfProduct> page = new Page<StoreSelfProduct>(request, response);
		String currentId = getSelectPage(page,  parent, status);
		Page<StoreSelfProduct> current_page = storeSelfProductService.find(page, productName, category_id, status); 
		model.addAttribute("parent", parent);
		model.addAttribute("status", status);
		model.addAttribute("productName", productName);
		model.addAttribute("currentId", currentId);
		model.addAttribute("page", current_page);
		return "modules/base/storeSelfProductList";
	}

	@RequestMapping(value = "form")
	public String form(StoreSelfProduct storeSelfProduct, ModelMap modelMap) {
		CacheUtils.put("select_selfProduct_id", storeSelfProduct.getId());
		StoreSelfProductCategory parent = (StoreSelfProductCategory)modelMap.get("parent");
		CacheUtils.put("select_selfProductCategory_id", parent.getId());
		storeSelfProduct.setStoreSelfProductCategory(parent);
		
		modelMap.addAttribute("storeSelfProduct", storeSelfProduct);
		return "modules/base/storeSelfProductForm";
	}

	@RequestMapping(value = "save")
	public String save(@RequestParam("photoFile") MultipartFile photoFile,
			StoreSelfProduct storeSelfProduct, Model model, RedirectAttributes redirectAttributes) {
		Long id = storeSelfProduct.getId();
		Store store = StoreUtils.getStore();
		storeSelfProduct.setStore(store);
		storeSelfProduct.setStatus(StoreSelfProduct.FLAG_ENABLE);
		try{
			String fileUrl = "";
			if (!photoFile.isEmpty()) {
				String oldUrl = storeSelfProduct.getImage();
				if(!StringUtils.isEmpty(oldUrl)) {
					OSSServer.delete(oldUrl);
				}
				fileUrl = OSSServer.save(photoFile);
				storeSelfProduct.setImage(fileUrl);
			}	
			storeSelfProductService.save(storeSelfProduct);
		} catch(Exception e) {
			addMessage(redirectAttributes, "保存店面自营产品'" + storeSelfProduct.getName() + "'失败");
			return "redirect:"+Global.ADMIN_PATH+"/base/storeSelfProduct/form";
		}
		if (!beanValidator(model, storeSelfProduct)){
			return form(storeSelfProduct, (ModelMap)model);
		}
		if(id == null) {
			StoreProduct storeProduct = new StoreProduct();
			storeProduct.setStore(store);
			storeProduct.setProduct_type(StoreProduct.TYPE_SELF);
			storeProduct.setAmount(0);
			storeProduct.setStoreSelfProduct(storeSelfProduct);
			storeProductService.save(storeProduct);
		}
		Long category_id = storeSelfProduct.getStoreSelfProductCategory().getId();
		addMessage(redirectAttributes, "保存店面自营产品'" + storeSelfProduct.getName() + "'成功");
		return "redirect:"+Global.ADMIN_PATH+"/base/storeSelfProduct/list?category_id=" + category_id;
	}
	
	@RequestMapping(value = "status")
	public String changeStatus(StoreSelfProduct storeSelfProduct, ModelMap modelMap, RedirectAttributes redirectAttributes) {
		StoreSelfProductCategory parent = (StoreSelfProductCategory)modelMap.get("parent");
		Long category_id = parent.getId();
		try {
			storeSelfProductService.changeStatus(storeSelfProduct);
			addMessage(redirectAttributes, "产品状态改变成功");
		} catch (Exception e) {
			addMessage(redirectAttributes, "产品正在使用中，无法改变状态！");
		}
		return "redirect:"+Global.ADMIN_PATH+"/base/storeSelfProduct/list?category_id=" + category_id;
	}
}
